/**
 * 全局初始化
 * @author huangchunmao
 * @email sujinw@qq.com
 * @date 2020/6/8
*/
import FastClick from 'fastclick'
import Vconsole from 'vconsole'

const vConsole = new Vconsole()
export default vConsole

/**
 * 初始化Rem
 */
function initRem () {
  const cale = window.screen.availWidth > 750 ? 2 : window.screen.availWidth / 375
  window.document.documentElement.style.fontSize = `${100 * cale}px`
}
document.addEventListener('DOMContentLoaded', initRem, false)

/**
 * 重新加载rem
 */
window.addEventListener('resize', function () {
  initRem()
  if (
    document.activeElement.tagName === 'INPUT' ||
    document.activeElement.tagName === 'TEXTAREA'
  ) {
    window.setTimeout(function () {
      if ('scrollIntoView' in document.activeElement) {
        document.activeElement.scrollIntoView(false)
      } else {
        document.activeElement.scrollIntoViewIfNeeded(false)
      }
    }, 0)
  }
})

document.addEventListener('focusout', () => {
  setTimeout(() => {
    const height = document.documentElement.scrollTop || document.body.scrollTop
    window.scrollTo(0, height + 1)
  }, 20)
})

// ============================= fast click ===================================
const u = navigator.userAgent
const deviceIsIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
FastClick.prototype.focus = function (targetElement) {
  var length
  if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
    length = targetElement.value.length
    targetElement.setSelectionRange(length, length)
    targetElement.focus()
  } else {
    targetElement.focus()
  }
}
FastClick.attach(document.body)
// ============================= 切换屏 ===================================
window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', onorientationchange, false)
function onorientationchange () {
  initRem()
}
